package com.suneee.industry.dao.impl;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.suneee.context.page.Page;
import com.suneee.context.page.Sort;
import com.suneee.context.page.Sort.Order;
import com.suneee.core.util.StringUtils;
import com.suneee.industry.bean.IndustrySearchBean;
import com.suneee.industry.dao.IndustryDao;
import com.suneee.industry.entity.Industry;
import com.suneee.orm.GenericDao;
import com.suneee.orm.util.WhereClauseBuilder;

@Repository("industryDao")
public class IndustryDaoImpl extends GenericDao<Industry, Integer>implements IndustryDao {

	@Override
	public boolean existsName(String name) {
		return this.exists("name", name);
	}

	/**
	 * 判断是否重复
	 * 
	 * @param name
	 * @param value
	 * @return
	 */
	private boolean exists(Object name, Object value) {
		List<Industry> list = this.selectWhere(name + " = ? ", value);
		return list != null && list.size() > 0;
	}

	@Override
	public boolean existsId(int id) {
		return this.exists("industry_id", id);
	}

	@Override
	public void updateIndustry(Industry industry) {
		StringBuffer sql = new StringBuffer();
		sql.append("update t_industry set ");
		sql.append(" name=? ");
		sql.append(" , order_number=? ");
		sql.append(" where industry_id=? ");
		Object[] arg = new Object[3];
		arg[0] = industry.getName();
		arg[1] = industry.getOrderNumber();
		arg[2] = industry.getIndustryId();
		this.executeUpdate(sql.toString(), arg);

	}

	@Override
	public Page<Industry> findIndustry(IndustrySearchBean bean) {
		if (bean == null) {
			bean = new IndustrySearchBean();
		}
		WhereClauseBuilder builder = new WhereClauseBuilder();
		builder.contains("name", bean.getName());
		bean.setPageNumber(bean.getPageNumber() == 0 ? 1 : bean.getPageNumber());
		bean.setPageSize(bean.getPageSize() == 0 ? 10 : bean.getPageSize());
		bean.setSort((bean.getSort() == null || StringUtils.isEmpty(bean.getSort().getOrderByClause()))
				? new Sort("order_number", Order.ASC) : bean.getSort());
		return selectWhere(builder.getSql(), bean, builder.getArgs());
	}

	@Override
	public List<Industry> listIndustry(String name) {
		WhereClauseBuilder wcb = new WhereClauseBuilder();
		wcb.contains("name",name);
		return this.selectWhere(wcb.getSql(),new Sort("order_number", Order.ASC),wcb.getArgs());
	}
}
